<template>
  <!-- 根据 showCheckbox 属性来决定显示哪个区域 -->
  <ContentWrap>
    <!-- tabs切换 -->
    <el-tabs v-model="activeTab" class="mb-15px" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="item in hazardTypes"
        :key="item.value"
        :label="item.label"
        :name="item.value"
      />
    </el-tabs>

    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="flex items-center flex-wrap"
    >
      <el-form-item label="首字母" prop="letter">
        <el-input
          v-model="queryParams.letter"
          clearable
          placeholder="请输入首字母"
          @keyup.enter="handleQuery"
        />

      </el-form-item>
      <el-form-item label="中文名" prop="cnName">
        <el-input
          v-model="queryParams.cnName"
          clearable
          placeholder="请输入中文名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-1px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-1px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['system:hazards:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-1px" icon="ep:plus" />
          新增危害
        </el-button>
      </el-form-item>
      <el-form-item class="ml-auto">
        <el-button type="primary" @click="handleSave"> 确定危害 </el-button>
        <el-button type="primary" @click="closeDialog"> 取消 </el-button>
        <el-button circle @click="showFormComp = !showFormComp">
          <Icon :icon="showFormComp ? 'ep:arrow-up' : 'ep:arrow-down'" />
        </el-button>
      </el-form-item>
      <div class="letter-quick-select">
        <el-tag
          v-for="letter in alphabetOptions"
          :key="letter"
          class="letter-tag"
          effect="plain"
          size="small"
          :type="queryParams.letter === letter ? 'primary' : 'info'"
          @click="handleLetterSelect(letter)"
        >
          {{ letter }}
        </el-tag>
      </div>
    </el-form>
  </ContentWrap>

  <!-- 已选中标签展示区域 -->
  <ContentWrap v-if="showCheckbox">
    <div class="mt-15px">
      <div class="mb-10px text-[14px] font-bold flex items-center justify-between">
        <span>已选择的危害因素：</span>
        <el-button
          v-if="uniqueSelectedTags.length > 0"
          type="primary"
          link
          size="small"
          @click="handleClearSelected"
        >
          <Icon icon="ep:delete" class="mr-1px" />
          清空
        </el-button>
      </div>
      <div class="flex flex-wrap gap-2">
        <template v-for="tag in uniqueSelectedTags" :key="tag.name">
          <el-tag
            :class="['mr-5px mb-5px', `hazard-type-${tag.type}`, 'is-selected']"
            closable
            round
            @close="handleUniqueTagClose(tag)"
          >
            {{ tag.name }}
            <span v-if="tag.onlyReco" class="reco-badge">仅识别</span>
          </el-tag>
        </template>
      </div>
    </div>
  </ContentWrap>

  <!-- 标签选择区域 -->
  <ContentWrap v-if="showCheckbox">
    <div class="mt-15px">
      <div class="mb-10px text-[14px] font-bold flex items-center justify-between">
        <span>危害因素列表：</span>
        <div class="flex items-center gap-2">
          <el-input
            size="small"
            v-model="quickCnName"
            class="quick-add-input"
            placeholder="快速添加危害（仅识别）"
            clearable
          >
            <template #append>
              <el-button
                size="small"
                type="primary"
                :loading="quickAddLoading"
                :disabled="!quickCnName || !quickCnName.trim()"
                @click="handleQuickAdd"
              >
                添加
              </el-button>
            </template>
          </el-input>
          <el-button
            v-if="allHazardsList.length > 100"
            type="text"
            size="small"
            @click="toggleExpanded"
          >
            {{ isExpanded ? '收起' : `展开全部(${allHazardsList.length})` }}
            <Icon :icon="isExpanded ? 'ep:arrow-up' : 'ep:arrow-down'" class="ml-1" />
          </el-button>
        </div>
      </div>
      <div
        ref="hazardContainerRef"
        class="flex flex-wrap gap-2 hazard-tags-container"
        tabindex="0"
        @keydown="handleHazardKeydown"
        @focus="handleHazardContainerFocus"
      >
        <el-tag
          v-for="(item, index) in displayedHazardsList"
          :key="item.id"
          :class="[
            'mr-5px mb-5px cursor-pointer',
            { 'is-selected': isSelected(item) },
            { 'is-focused': focusedHazardIndex === index },
            `hazard-type-${item.type}`
          ]"
          effect="plain"
          round
          ref="hazardTagRefs"
          @click="handleTagClick(item, index)"
        >
          {{ item.cnName }}
          <span v-if="(item as any).onlyReco" class="reco-badge">仅识别</span>
        </el-tag>
        <!-- 省略号提示 -->
        <el-tag
          v-if="!isExpanded && allHazardsList.length > 100"
          class="mr-5px mb-5px cursor-pointer ellipsis-tag"
          effect="plain"
          round
          @click="toggleExpanded"
        >
          ...还有{{ allHazardsList.length - 100 }}个
        </el-tag>
      </div>
    </div>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <JobSurveyHazardsForm
    v-show="showFormComp"
    ref="formRef"
    @success="handleFormSuccess"
    @type-change="handleFormTypeChange"
  />
</template>

<script lang="ts" setup>
import type { ComponentPublicInstance } from 'vue'
import { nextTick, onBeforeUpdate, onMounted, onUnmounted } from 'vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { HazardsApi, HazardsVO } from '@/api/system/hazards'
import JobSurveyHazardsForm from './JobSurveyHazardsForm.vue'

/** 危害因素 列表 */
defineOptions({ name: 'Hazards' })

const loading = ref(true) // 列表的加载中
const list = ref<HazardsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// 定义类型接口
interface HazardType {
  label: string
  value: string
}

// 修改响应式变量的类型声明
const activeTab = ref<string>('') // 当前激活的 tab
const hazardTypes = ref<HazardType[]>([]) // 危害类型选项
// 添加清空所有已选的处理函数
const handleClearSelected = () => {
  ElMessageBox.confirm('确认清空所有已选择的危害因素吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    internalSelected.value = []
    // 触发 select 事件通知父组件更新
    emit('select', [])
  }).catch(() => {})
}
// 修改 queryParams 的类型
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: '' as string, // 修改为字符串类型，设置初始值
  cnName: undefined as string | undefined,
  letter: undefined as string | undefined,
  enName: undefined as string | undefined,
  cas: undefined as string | undefined,
  mac: undefined as string | undefined,
  pcTwa: undefined as string | undefined,
  pcStel: undefined as string | undefined,
  totalDust: undefined as string | undefined,
  expiratoryDust: undefined as string | undefined,
  healthEffects: undefined as string | undefined
})
const queryFormRef = ref() // 搜索的表单

// 首字母快捷选择
const alphabetOptions = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')

const handleLetterSelect = (letter: string) => {
  queryParams.letter = letter
}

// 危害因素标签键盘导航
const hazardContainerRef = ref<HTMLElement | null>(null)
const hazardTagRefs = ref<Array<ComponentPublicInstance | HTMLElement>>([])
const focusedHazardIndex = ref(-1)

const focusHazardList = () => {
  if (!props.showCheckbox) return
  nextTick(() => {
    hazardContainerRef.value?.focus()
  })
}

// 新增：存储所有危害因素的列表
const allHazardsList = ref<HazardsVO[]>([])

// 修改 props 定义，明确类型
const props = defineProps<{
  showCheckbox: boolean
  selectedHazards: Array<{
    id: number
    type: number | string
    cnName: string
    onlyReco?: boolean
    letter?: string
    enName?: string
    cas?: string
    mac?: string
    pcTwa?: string
    pcStel?: string
    totalDust?: string
    expiratoryDust?: string
    healthEffects?: string
    isDeleted?: boolean
    sampling?: {
      sampleDays: number
      pointCount: number
      sampleCount: number
      contactHours: number
      startDay: number
      timeType: 'long' | 'short'
      sampleType: 'fix' | 'personal' | 'none'
      isCustomTime?: boolean
      sampleDuration?: number
    }
  }>
}>()

// 新增 emit 定义
const emit = defineEmits(['select', 'closeDialog', 'handleSave'])

// 修改内部选中状态的类型定义
const internalSelected = ref<typeof props.selectedHazards>([])

// 修改判断是否选中的方法
const isSelected = (item: HazardsVO) => {
  const result = internalSelected.value.some((selected) => {
    // 将已选择的名称按逗号拆分
    const selectedNames = selected.cnName.split('、')
    // 检查当前项的名称是否在已选择的名称列表中
    const isIncluded = selectedNames.includes(item.cnName)
    return isIncluded
  })
  return result
}
// 快速添加（仅识别）
const quickCnName = ref('')
const quickAddLoading = ref(false)
const currentTabLabel = computed(() =>
  hazardTypes.value.find((h) => h.value === activeTab.value)?.value || ''
)

// 工具：按中文名拆分（兼容多种分隔符）
const splitNames = (s: string) =>
  (s || '')
    .split('、') // 只保留中文顿号作为分隔符
    .map((t) => t.trim())
    .filter((t) => !!t);
// 已选择危害因素去重（按名称）用于显示
const uniqueSelectedTags = computed(() => {
  const seen = new Set<string>()
  const result: Array<{ name: string; type: any; onlyReco?: boolean; item: any }> = []
  for (const item of internalSelected.value || []) {
    for (const name of splitNames(item?.cnName || '')) {
      if (!seen.has(name)) {
        seen.add(name)
        result.push({ name, type: item?.type, onlyReco: (item as any)?.onlyReco === true, item })
      }
    }
  }
  return result
})

// 关闭单个去重后的标签（定位到原始项，并移除该名称）
const handleUniqueTagClose = (tag: { name: string; item: any }) => {
  if (!tag) return
  handleTagClose(tag.item, tag.name)
}
const createHazardsByName = async (name: string) => {
  await HazardsApi.createHazards({ cnName: name, onlyReco: true, type: currentTabLabel.value })
}
const handleQuickAdd = async () => {
  const name = quickCnName.value?.trim()
  if (!name) return
  try {
    quickAddLoading.value = true
    await createHazardsByName(name)
    quickCnName.value = ''
    await Promise.all([getList(), getAllHazards()])
  } finally {
    quickAddLoading.value = false
  }
}

// 修改标签点击处理方法
const handleTagClick = (item: HazardsVO, tagIndex?: number) => {
  if (!props.showCheckbox) return

  if (typeof tagIndex === 'number') {
    updateFocusAndScroll(tagIndex)
  }

  focusHazardList()

  console.log('点击项', JSON.stringify(item))

  console.log('当前已选择', JSON.stringify(internalSelected.value))

  // 查找是否已存在包含该名称的项
  const index = internalSelected.value.findIndex((selected) => {
    const names = selected.cnName.split('、')
    return names.includes(item.cnName)
  })
  console.log('查找索引:', index)

  if (index > -1) {
    // 如果已经选中，从名称列表中移除
    const names = internalSelected.value[index].cnName.split('、')
    const nameIndex = names.indexOf(item.cnName)
    console.log('名称处理:', {
      当前名称: item.cnName,
      已选择名称列表: names,
      名称索引: nameIndex
    })

    if (nameIndex > -1) {
      names.splice(nameIndex, 1)
      if (names.length > 0) {
        // 如果还有其他名称，更新cnName
        internalSelected.value[index] = {
          ...internalSelected.value[index],
          cnName: names.join('、')
        }
        console.log('更新后的项:', internalSelected.value[index])
      } else {
        // 如果没有其他名称，删除整个项
        internalSelected.value.splice(index, 1)
        console.log('删除整个项')
      }
    }
  } else {
    // 如果未选中，添加新项
    const newItem = {
      id: item.id || 0,
      type: item.type,
      cnName: item.cnName,
      onlyReco: (item as any).onlyReco === true,
      letter: item.letter || '',
      enName: item.enName,
      cas: item.cas,
      mac: item.mac,
      pcTwa: item.pcTwa,
      pcStel: item.pcStel,
      totalDust: item.totalDust,
      expiratoryDust: item.expiratoryDust,
      healthEffects: item.healthEffects
    } as (typeof props.selectedHazards)[0]

    internalSelected.value.push(newItem)
    console.log('添加新项:', newItem)
  }

  console.log('更新后的已选择列表2:', JSON.stringify(internalSelected.value))
  emit('select', [...internalSelected.value])
  openForm('edit', item.id)
}

const handleTagClose = (item: (typeof props.selectedHazards)[0], specificName?: string) => {
  console.log('关闭项', JSON.stringify(item))
  console.log('特定名称', JSON.stringify(specificName))

  // 查找包含特定名称的项
  const index = internalSelected.value.findIndex((selected) => {
    const names = selected.cnName.split('、')
    return specificName ? names.includes(specificName) : names.includes(item.cnName)
  })
  console.log('查找索引:', index)

  if (index > -1) {
    const names = internalSelected.value[index].cnName.split('、')
    const nameToRemove = specificName || item.cnName
    const nameIndex = names.indexOf(nameToRemove)
    console.log('名称处理:', {
      要移除的名称: nameToRemove,
      已选择名称列表: names,
      名称索引: nameIndex
    })

    if (nameIndex > -1) {
      names.splice(nameIndex, 1)
      if (names.length > 0) {
        // 更新剩余的名称
        internalSelected.value[index] = {
          ...internalSelected.value[index],
          cnName: names.join('、')
        }
        console.log('更新后的项:', internalSelected.value[index])
      } else {
        // 如果没有剩余名称，删除整个项
        internalSelected.value.splice(index, 1)
        console.log('删除整个项')
      }
    }
    console.log('更新后的已选择列表1:', JSON.stringify(internalSelected.value))
    emit('select', internalSelected.value)
  }
}

// 修改：清除选中状态
const clearGlobalSelected = () => {
  internalSelected.value = []
}

const handleSave = () => {
  emit('handleSave')
}

const closeDialog = () => {
  emit('closeDialog')
}

// 表单提交成功：同时刷新表格和标签
const handleFormSuccess = async () => {
  await Promise.all([getList(), getAllHazards()])
}

// 子表单危害分类变化时，同步高亮 Tab（仅在新增时联动）
const handleFormTypeChange = (newType: string) => {
  if (!newType) return
  if (currentFormMode.value === 'create') {
    activeTab.value = newType
  }
}

// 暴露方法给父组件
defineExpose({
  clearGlobalSelected
})

// 获取危害类型选项
const getHazardTypes = () => {
  hazardTypes.value = getStrDictOptions(DICT_TYPE.HAZARD_TYPE)
  // 默认选中第一个 tab，并设置初始 type
  if (hazardTypes.value.length > 0) {
    activeTab.value = hazardTypes.value[0].value
    queryParams.type = activeTab.value // 确保初始化时设置 type
  }
}

// tab切换处理
const handleTabClick = async (tab: any) => {
  queryParams.type = tab.props.name
  queryParams.cnName = ''
  queryParams.letter = ''
  // 切换tab时重置为收起状态
  isExpanded.value = false
  // 切换tab时重置待选框为第一个
  focusedHazardIndex.value = 0

  // 同步给子表单（仅在新增时联动）
  if (showFormComp.value && currentFormMode.value === 'create') {
    formRef.value?.setType?.(queryParams.type)
  }
  await Promise.all([handleQuery(), getAllHazards()]) // 同时更新表格和标签数据
  focusHazardList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 不需要在这里重新设置 type，因为已经在 tab 切换时设置了
    const data = await HazardsApi.getHazardsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  // 搜索时也重置为收起状态
  isExpanded.value = false
  // 搜索时重置待选框为第一个
  focusedHazardIndex.value = 0
  await Promise.all([getList(), getAllHazards()]) // 同时更新表格和标签数据
  focusHazardList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 重置时保留当前选中的类型
  queryParams.type = activeTab.value
  // 重置时也重置为收起状态
  isExpanded.value = false
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const currentFormMode = ref<'create' | 'edit' | ''>('')
const openForm = (type: string, id?: number) => {
  console.log('type:', type)
  console.log('id:', id)
  currentFormMode.value = type === 'create' ? 'create' : 'edit'
  if (!showFormComp.value) {
    showFormComp.value = true
    nextTick(() => {
      formRef.value?.open(type, id, activeTab.value)
    })
    return
  }
  formRef.value?.open(type, id, activeTab.value)
}

// 新增：获取所有危害因素的方法
const getAllHazards = async () => {
  try {
    const data = await HazardsApi.getHazardsPage({
      ...queryParams,
      pageSize: 999, // 设置较大的页面大小以获取所有数据
      pageNo: 1
    })
    allHazardsList.value = data.list
  } catch (error) {
    console.error('获取所有危害因素失败:', error)
  }
}

/** 初始化 **/
onMounted(async () => {
  window.addEventListener('keydown', handleGlobalArrowKey, true)
  getHazardTypes() // 获取危害类型选项并设置初始 type
  await Promise.all([getList(), getAllHazards()]) // 同时获取表格和标签数据
  focusHazardList()
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleGlobalArrowKey, true)
})

// 修改：处理标签关闭

// 在 setup 中添加新的响应式变量
const showQuickAdd = ref(false)
const showFormComp = ref(false)
const isExpanded = ref(false) // 控制危害因素列表展开/收起状态

// 计算属性：根据展开状态显示的危害因素列表
const displayedHazardsList = computed(() => {
  if (isExpanded.value || allHazardsList.value.length <= 100) {
    return allHazardsList.value
  }
  return allHazardsList.value.slice(0, 100)
})

// 切换展开/收起状态
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

const getHazardTagElement = (refItem?: ComponentPublicInstance | HTMLElement | null) => {
  if (!refItem) return null
  const possibleComponent = refItem as ComponentPublicInstance
  // @ts-ignore
  return (possibleComponent.$el as HTMLElement) || (refItem as HTMLElement)
}

interface HazardTagMeta {
  idx: number
  el: HTMLElement
  rect: DOMRect
}

const getHazardTagMetas = (): HazardTagMeta[] => {
  return hazardTagRefs.value
    .map((refItem, idx) => {
      const el = getHazardTagElement(refItem)
      if (!el) return null
      return {
        idx,
        el,
        rect: el.getBoundingClientRect()
      } as HazardTagMeta
    })
    .filter((meta): meta is HazardTagMeta => meta !== null)
}

const updateFocusAndScroll = (index: number) => {
  focusedHazardIndex.value = index
  nextTick(() => {
    if (focusedHazardIndex.value < 0) return
    const el = getHazardTagElement(hazardTagRefs.value[focusedHazardIndex.value])
    el?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' })
  })
}

const moveFocus = (direction: 'left' | 'right' | 'up' | 'down') => {
  const metas = getHazardTagMetas()
  if (!metas.length) return

  const clampIndex = (idx: number) => Math.min(Math.max(idx, 0), metas.length - 1)
  const currentIndex = focusedHazardIndex.value === -1 ? 0 : focusedHazardIndex.value

  // 左右键直接按索引移动
  if (direction === 'left' || direction === 'right') {
    const offset = direction === 'left' ? -1 : 1
    updateFocusAndScroll(clampIndex(currentIndex + offset))
    return
  }

  // 上下键基于位置计算
  const currentMeta = metas[clampIndex(currentIndex)]
  if (!currentMeta) return

  const currentRect = currentMeta.rect
  const threshold = 4
  const pickClosest = (candidates: HazardTagMeta[], scoreFn: (meta: HazardTagMeta) => number) => {
    return candidates.reduce((best, meta) => {
      if (!best) return meta
      const bestScore = scoreFn(best)
      const nextScore = scoreFn(meta)
      if (nextScore < bestScore) return meta
      if (nextScore === bestScore) {
        const bestHorizontal = Math.abs(best.rect.left - currentRect.left)
        const nextHorizontal = Math.abs(meta.rect.left - currentRect.left)
        return nextHorizontal < bestHorizontal ? meta : best
      }
      return best
    }, null as HazardTagMeta | null)
  }

  let targetMeta: HazardTagMeta | null = null
  if (direction === 'up') {
    const candidates = metas.filter((meta) => meta.rect.bottom <= currentRect.top - threshold)
    if (candidates.length) {
      targetMeta = pickClosest(candidates, (meta) => currentRect.top - meta.rect.bottom)
    }
  } else if (direction === 'down') {
    const candidates = metas.filter((meta) => meta.rect.top >= currentRect.bottom + threshold)
    if (candidates.length) {
      targetMeta = pickClosest(candidates, (meta) => meta.rect.top - currentRect.bottom)
    }
  }

  if (targetMeta) {
    updateFocusAndScroll(targetMeta.idx)
  }
}

const arrowKeys = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'])

const handleGlobalArrowKey = (event: KeyboardEvent) => {
  if (!arrowKeys.has(event.key)) return
  if (!props.showCheckbox) return
  if (!displayedHazardsList.value.length) return

  const containerEl = hazardContainerRef.value
  if (!containerEl) return

  const activeElement = document.activeElement as HTMLElement | null
  if (activeElement && (containerEl === activeElement || containerEl.contains(activeElement))) {
    return
  }

  event.preventDefault()
  event.stopPropagation()
  focusHazardList()
  handleHazardKeydown(event)
}

const handleHazardKeydown = (event: KeyboardEvent) => {
  if (!displayedHazardsList.value.length) return
  event.stopPropagation()

  const keyMap: Record<string, () => void> = {
    ArrowRight: () => moveFocus('right'),
    ArrowDown: () => moveFocus('down'),
    ArrowLeft: () => moveFocus('left'),
    ArrowUp: () => moveFocus('up'),
    Home: () => updateFocusAndScroll(0),
    End: () => updateFocusAndScroll(displayedHazardsList.value.length - 1),
    Enter: selectCurrentHazard,
    ' ': selectCurrentHazard
  }

  const handler = keyMap[event.key]
  if (handler) {
    event.preventDefault()
    handler()
  }
}

const handleHazardContainerFocus = () => {
  if (!displayedHazardsList.value.length) return
  if (focusedHazardIndex.value === -1) {
    updateFocusAndScroll(0)
  }
}

const selectCurrentHazard = () => {
  const targetIndex = focusedHazardIndex.value === -1 ? 0 : focusedHazardIndex.value
  const target = displayedHazardsList.value[targetIndex]
  if (target) handleTagClick(target, targetIndex)
}

onBeforeUpdate(() => {
  hazardTagRefs.value = []
})

// 修改监听器
watch(
  () => props.selectedHazards,
  (newVal) => {
    if (newVal) {
      // 确保深拷贝数组
      internalSelected.value = JSON.parse(JSON.stringify(newVal))
      // internalSelected.value = JSON.parse(JSON.stringify(newVal.filter(x => x.isDeleted==false)))
    }
  },
  { immediate: true, deep: true }
)

watch(
  displayedHazardsList,
  (newList) => {
    if (!newList.length) {
      focusedHazardIndex.value = -1
      return
    }
    const maxIndex = newList.length - 1
    if (focusedHazardIndex.value === -1) {
      updateFocusAndScroll(0)
    } else if (focusedHazardIndex.value > maxIndex) {
      updateFocusAndScroll(maxIndex)
    }
    focusHazardList()
  },
  { immediate: true }
)

watch(
  () => queryParams.letter,
  async (newVal, oldVal) => {
    if (newVal === oldVal) return
    await handleQuery()
  }
)

watch(
  () => props.showCheckbox,
  (val) => {
    if (val) {
      focusHazardList()
    }
  }
)

watch(
  () => queryParams.cnName,
  async (newVal, oldVal) => {
    if (newVal === oldVal) return
    await handleQuery()
  }
)
</script>

<style lang="scss" scoped>
.el-tag {
  position: relative;
  padding-right: 20px; // 为徽标留出空间

  .reco-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background-color: var(--el-color-danger);
    color: white;
    font-size: 10px;
    padding: 2px 4px;
    border-radius: 8px;
    transform: scale(0.8);
    white-space: nowrap;
  }

  &.cursor-pointer {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: var(--el-color-primary-light-8);
    }
  }

  &.is-focused {
    box-shadow: 0 0 0 2px var(--el-color-primary) inset;
    border-color: var(--el-color-primary);
  }

  // 选中状态样式
  &.is-selected {
    .el-tag__close {
      color: inherit;

      &:hover {
        color: #fff;
        background-color: currentColor;
      }
    }
  }

  // 不同类型的危害标签颜色
  &.hazard-type-1 {
    // 物理因素
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #d9ecff;

    &.is-selected {
      color: #409eff;
      background-color: #d9ecff;
      border-color: #409eff;
    }
  }

  &.hazard-type-2 {
    // 化学因素
    color: #67c23a;
    background-color: #f0f9eb;
    border-color: #e1f3d8;

    &.is-selected {
      color: #67c23a;
      background-color: #e1f3d8;
      border-color: #67c23a;
    }
  }

  &.hazard-type-3 {
    // 生物因素
    color: #e6a23c;
    background-color: #fdf6ec;
    border-color: #faecd8;

    &.is-selected {
      color: #e6a23c;
      background-color: #faecd8;
      border-color: #e6a23c;
    }
  }

  &.hazard-type-4 {
    // 人体工效
    color: #f56c6c;
    background-color: #fef0f0;
    border-color: #fde2e2;

    &.is-selected {
      color: #f56c6c;
      background-color: #fde2e2;
      border-color: #f56c6c;
    }
  }

  &.hazard-type-5 {
    // 其他
    color: #909399;
    background-color: #f4f4f5;
    border-color: #e9e9eb;

    &.is-selected {
      color: #909399;
      background-color: #e9e9eb;
      border-color: #909399;
    }
  }

  // 省略号标签样式
  &.ellipsis-tag {
    color: #909399;
    background-color: #f4f4f5;
    border-color: #e9e9eb;
    border-style: dashed;

    &:hover {
      background-color: #e9e9eb;
      border-color: #909399;
    }
  }
}

.quick-add-input {
  width: 200px;

  :deep(.el-input-group__append) {
    padding: 0;

    .el-button {
      margin: 0;
      border: none;
      height: 100%;
      padding: 0 10px;
    }
  }
}

.letter-quick-select {
  display: flex;
}

.letter-tag {
  cursor: pointer;
}

.hazard-tags-container {
  outline: none;
}

.hazard-tags-container:focus-visible {
  outline: 2px solid var(--el-color-primary);
  outline-offset: 4px;
}
</style>
